package com.coreservlets.jsf.ss06;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.faces.model.SelectItem;

public class LanguageUtils 
{
	private static String[] languages = { "Java", "JavaScript", "C#", "C++", "PHP", "Python", "Perl", "Ruby", "Scala" };
	
	private static List<SelectItem> availableLanguages;
	
	static
	{
		availableLanguages = new ArrayList<SelectItem>();
		for( String language: languages )
		{
			availableLanguages.add( new SelectItem( language ) );
		}
	}
	
	public static String findMostPopularLanguage( int index )
	{
		int numLanguages = languages.length;
		
		if( index >= numLanguages )
		{
			index = numLanguages - 1;
		}
		
		return( languages[ index ]);
	}
	
	public static String[] languageArray()
	{
		return( languages );
	}
	
	public static List< SelectItem > languageList() 
	{
		return( availableLanguages );
	}
	
	public static List<String> randomLanguages( int numLanguages )
	{
		if( numLanguages >= languages.length )
		{
			return( Arrays.asList( languages ));
		}
		else
		{
			List< String > randomLanguages = new ArrayList<String>();
			
			for (int i = 0; i < numLanguages; i++ ) 
			{
				randomLanguages.add( uniqueRandomLanguage( randomLanguages, languages ) );
			}
			
			return randomLanguages;
		}
	}
	
	private static String uniqueRandomLanguage( List<String> previousLanguage, String[] newLanguageChoices )
	{
		String newLanguage = RandomUtils.randomElement( newLanguageChoices );
		
		if( !previousLanguage.contains( newLanguage ))
		{
			return( newLanguage );
		}
		else
		{
			return( uniqueRandomLanguage(previousLanguage, newLanguageChoices));
		}
	}
	
	private LanguageUtils(){};
}
